/*
 * @Description: user仓库
 * @Author: LDM
 * @Date: 2021-09-11 11:48:42
 * @LastEditors: LDM
 * @LastEditTime: 2021-09-30 16:33:38
 */
import { defineStore, acceptHMRUpdate } from 'pinia'
import { pinia } from '/@/store'
import { login } from '/@/apis/user/user'
interface IUserState {
  roles: number[]
  avatar: string
  userName: string
  token: string
}

const createUserState = (): IUserState => ({
  avatar: '',
  userName: '',
  token: '',
  roles: [] as number[]
})
export const useUserStore = defineStore('user', {
  state: createUserState,
  actions: {
    ResetState() {
      Object.assign(this, createUserState())
    },
    SetToken(token: string) {
      this.token = token
    },
    SetUserName(userName: string) {
      this.userName = userName
    },
    SetAvatar(avatar: string) {
      this.avatar = avatar
    },
    SetRoles(roles: number[]) {
      this.roles = roles
    },
    async GetUserInfoAction() {
      this.roles = [] as number[]
    },
    async Login() {
      const { token } = await login()
      this.SetToken(token)
    }
  }
})

/**
 * @description: 在setup外使用仓库时调用
 * @return {*} 返回UserStore
 */
export function useUserStoreWithOut() {
  return useUserStore(pinia)
}

// make sure to pass the right store definition, `useAuth` in this case.
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}
